//
//  LoginViewController.m
//  51易借
//
//  Created by 张睿 on 2017/8/17.
//  Copyright © 2017年 张睿. All rights reserved.
//

#import "LoginViewController.h"
#import "FindPasswordViewController.h"
#import "SetupViewController.h"
#import "AppDelegate.h"
#import "MainViewController.h"

@interface LoginViewController ()<UITextFieldDelegate>

@property (nonatomic, weak)UIView * topView;
@property (nonatomic, weak)UIImageView * logoImageView;
@property (nonatomic, weak)UIView * inputView;
@property (nonatomic, weak)UILabel * accountLabel;
@property (nonatomic, weak)UITextField * telTextField;
@property (nonatomic, weak)UIView * lineView;
@property (nonatomic, weak)UILabel * passwordLabel;
@property (nonatomic, weak)UITextField * passwordTextField;
@property (nonatomic, weak)UIButton * forgetButton;
@property (nonatomic, weak)UIButton * loginButton;
@property (nonatomic, weak)UIButton * setupButton;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldEditChanged:)
                                                name:@"UITextFieldTextDidChangeNotification" object:self.telTextField];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupNavBar];
    [self setupUI];
}


- (void)setupNavBar{
    
    self.title = @"登录";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(15 * SCREENH6, 5 * SCREENH6, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToLastView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
    
    self.navigationController.navigationBar.translucent=YES;
    UIColor *color=[UIColor clearColor];
    CGRect rect =CGRectMake(0,0,self.view.frame.size.width,64);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context =UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:(UIBarMetricsDefault)];
    
    self.navigationController.navigationBar.clipsToBounds=YES;
}



- (void)setupUI{
    [self setupForDismissKeyboard];
    UIView * topView = [UIView new];
    
    topView.backgroundColor = ColorWithRGB(0xff7907);
    
    self.topView = topView;
    
    [self.view addSubview:self.topView];
    
    
    UIImageView * logoImageView = [UIImageView new];
    
    logoImageView.image = [UIImage imageNamed:@"logo"];
    
    self.logoImageView = logoImageView;
    
    [self.view addSubview:self.logoImageView];
    
    
    UIView * inputView = [UIView new];
    
    inputView.backgroundColor = [UIColor whiteColor];
    inputView.layer.borderColor = [ColorWithRGB(0xe6e6e6) CGColor];
    inputView.layer.borderWidth = 0.5 * SCREENH6;
    
    self.inputView = inputView;
    
    [self.view addSubview:self.inputView];
    
    
    UILabel * accountLabel = [UILabel new];
    
    accountLabel.text = @"账号";
    accountLabel.textColor = ColorWithRGB(0x303c41);
    
    self.accountLabel = accountLabel;
    
    [self.view addSubview:self.accountLabel];
    
    
    UITextField * accountText = [[UITextField alloc] init];
    
    accountText.borderStyle = UITextBorderStyleNone;
    accountText.backgroundColor = [UIColor clearColor];
    accountText.layer.borderColor = [[UIColor clearColor] CGColor];
    //设置光标颜色
    accountText.tintColor = ColorWithRGB(0xa5a5a5);
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = ColorWithRGB(0xa5a5a5);
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    accountText.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入手机号码" attributes:attrs];
    accountText.textColor = ColorWithRGB(0x303c41);
    accountText.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 22 * SCREENH6, 0)];
    //设置显示模式为永远显示(默认不显示)
    accountText.leftViewMode = UITextFieldViewModeAlways;
    accountText.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    accountText.keyboardType = UIKeyboardTypeNumberPad;
    accountText.delegate = self;
    
    self.telTextField = accountText;
    
    [self.view addSubview:self.telTextField];
    
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0xe6e6e6);
    
    self.lineView = lineView;
    
    [self.view addSubview:self.lineView];
    
    
    UILabel * passwordLabel = [UILabel new];
    
    passwordLabel.text = @"密码";
    passwordLabel.textColor = ColorWithRGB(0x303c41);
    
    self.passwordLabel = passwordLabel;
    
    [self.view addSubview:self.passwordLabel];
    
    
    UITextField * passwordTextField = [[UITextField alloc] init];
    
    passwordTextField.borderStyle = UITextBorderStyleNone;
    passwordTextField.backgroundColor = [UIColor clearColor];
    passwordTextField.layer.borderColor = [[UIColor clearColor] CGColor];
    //设置光标颜色
    passwordTextField.tintColor = ColorWithRGB(0xa5a5a5);
    //修改占位符文字颜色
    passwordTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入6~8数字和字母组合" attributes:attrs];
    passwordTextField.textColor = ColorWithRGB(0x303c41);
    passwordTextField.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 22 * SCREENH6, 0)];
    //设置显示模式为永远显示(默认不显示)
    passwordTextField.leftViewMode = UITextFieldViewModeAlways;
    passwordTextField.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    passwordTextField.secureTextEntry = YES;
    
    self.passwordTextField = passwordTextField;
    
    [self.view addSubview:self.passwordTextField];
    
    
    UIButton * forgetButton = [UIButton new];
    //300 * 42
    [forgetButton setTitle:@"忘记密码？" forState:UIControlStateNormal];
    [forgetButton setBackgroundColor:[UIColor whiteColor]];
    [forgetButton setTitleColor:ColorWithRGB(0xff7907) forState:UIControlStateNormal];
    [forgetButton addTarget:self action:@selector(didFogetPasswordButton) forControlEvents:UIControlEventTouchUpInside];
    forgetButton.titleLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    
    self.forgetButton = forgetButton;
    
    [self.view addSubview:self.forgetButton];
    
    
    UIButton * loginButton = [UIButton new];
    //300 * 42
    [loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [loginButton setBackgroundImage:[UIImage imageNamed:@"登录"] forState:UIControlStateNormal];
    [loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginButton addTarget:self action:@selector(didLoginButton) forControlEvents:UIControlEventTouchUpInside];
    loginButton.titleLabel.font = [UIFont systemFontOfSize:14 * SCREENH6];
    
    self.loginButton = loginButton;
    
    [self.view addSubview:self.loginButton];
    
    
    UIButton * setupButton = [UIButton new];
    //300 * 42
    [setupButton setTitle:@"立即注册" forState:UIControlStateNormal];
    [setupButton setBackgroundImage:[UIImage imageNamed:@"立即注册"] forState:UIControlStateNormal];
    [setupButton setBackgroundColor:[UIColor whiteColor]];
    [setupButton setTitleColor:ColorWithRGB(0xff7907) forState:UIControlStateNormal];
    [setupButton addTarget:self action:@selector(didSetupButton) forControlEvents:UIControlEventTouchUpInside];
    setupButton.titleLabel.font = [UIFont systemFontOfSize:14 * SCREENH6];
    
    self.setupButton = setupButton;
    
    [self.view addSubview:self.setupButton];
}


- (void)viewDidLayoutSubviews{
    
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.mas_equalTo(self.view);
        make.height.mas_equalTo(192 * SCREENH6);
    }];
    
    [self.logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(90 * SCREENH6);
        make.width.mas_equalTo(147 * SCREENH6);
        make.height.mas_equalTo(49 * SCREENH6);
    }];
    
    [self.inputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.topView.mas_bottom).offset(6 * SCREENH6);
        make.leading.mas_equalTo(self.view).offset(5 * SCREENH6);
        make.trailing.mas_equalTo(self.view).offset(-5 * SCREENH6);
        make.height.mas_equalTo(106 * SCREENH6);
    }];
    
    [self.accountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.inputView).offset(15 * SCREENH6);
        make.leading.mas_equalTo(self.inputView).offset(20 * SCREENH6);
    }];
    
    [self.telTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(270 * SCREENH6);
        make.centerY.mas_equalTo(self.accountLabel);
        make.trailing.mas_equalTo(self.inputView);
        make.height.mas_equalTo(45 * SCREENH6);
    }];
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.inputView).offset(10 * SCREENH6);
        make.trailing.mas_equalTo(self.inputView).offset(-10 * SCREENH6);
        make.height.mas_equalTo(0.5 * SCREENH6);
        make.top.mas_equalTo(self.telTextField.mas_bottom).offset(5 * SCREENH6);
    }];
    
    [self.passwordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.accountLabel);
        make.top.mas_equalTo(self.lineView.mas_bottom).offset(15 * SCREENH6);
    }];
    
    [self.passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.mas_equalTo(self.telTextField);
        make.centerY.mas_equalTo(self.passwordLabel);
    }];
    
    
    [self.forgetButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.inputView.mas_bottom).offset(15 * SCREENH6);
        make.trailing.mas_equalTo(self.inputView.mas_trailing);
        make.width.mas_equalTo(70 * SCREENH6);
        make.height.mas_equalTo(20 * SCREENH6);
    }];
    
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.inputView.mas_bottom).offset(65 * SCREENH6);
        make.width.mas_equalTo(300 * SCREENH6);
        make.height.mas_equalTo(42 * SCREENH6);
    }];
    
    [self.setupButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.width.height.mas_equalTo(self.loginButton);
        make.top.mas_equalTo(self.loginButton.mas_bottom).offset(10 * SCREENH6);
    }];
}


//点击左侧按钮
- (void)backToLastView{
    
    if ([self.typeString isEqualToString:@"1"]) {
        
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        
        MainViewController *tabs = [[MainViewController alloc] init];
        
        appDelegate.window.rootViewController = tabs;
    }else{
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}


//点击忘记密码按钮
- (void)didFogetPasswordButton{
    
    FindPasswordViewController * findVC = [FindPasswordViewController new];
    
    [self.navigationController pushViewController:findVC animated:YES];
}


//点击登录按钮
- (void)didLoginButton{
    
    
    if(self.telTextField.text.length == 0)
    {
        [self showHint:@"请输入账号"];
        return;
    }
    if(self.passwordTextField.text.length == 0)
    {
        [self showHint:@"请输入密码"];
        return;
    }
    
    
    
    NSString * password = [self md5:self.passwordTextField.text];
    
    NSDictionary * parameters = @{@"userPhone":self.telTextField.text,@"password":password};
    
    [[NetworkTool shareManager] POST:@"user/login.json" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        
        NSString * code = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        
        if ([code isEqualToString:@"0"]) {
            
            DEF_SET_OBJECT([[responseObject objectForKey:@"data"] objectForKey:@"id"],userID);
            DEF_SET_OBJECT([[responseObject objectForKey:@"data"] objectForKey:@"token"],userToken);
            DEF_SET_OBJECT( [[responseObject objectForKey:@"data"] objectForKey:@"account"],myAccount);
            DEF_SET_OBJECT(self.telTextField.text,@"tel");
            
            AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            
            MainViewController *tabs = [[MainViewController alloc] init];
            
            appDelegate.window.rootViewController = tabs;
            
            
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseObject[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"==%@",error);
        
    }];
}


//点击注册按钮
- (void)didSetupButton{
    
    SetupViewController * setupVC = [SetupViewController new];
    
    [self.navigationController pushViewController:setupVC animated:YES];
}


//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
//{
//    if (textField == self.self.telTextField) {
//        if (textField.text.length > 10) {
//            
////            [self showHint:@"请输入正确的账号"];
//            
//            textField.text = [textField.text substringToIndex:11];
//        }
//    }
//    
//    return YES;
//    
//}

#pragma mark - Notification Method
-(void)textFieldEditChanged:(NSNotification *)obj
{

    if (self.telTextField.text.length > 10) {
        
        //            [self showHint:@"请输入正确的账号"];
        
        self.telTextField.text = [self.telTextField.text substringToIndex:11];
    }
}


//- (void)textFieldDidChange:(UITextField *)textField
//{
//    if (textField == self.self.telTextField) {
//        if (textField.text.length > 11) {
//            textField.text = [textField.text substringToIndex:10];
//        }
//    }
//}


//MD5 加密
- (NSString *) md5:(NSString *) input {
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return  output;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
